package com.yyh.jingdongsystem;

import java.io.*;
import java.util.*;

/*京东商城系统*/
//主系统类
public class MainSystem {
    private GoodsManager goodsManager;
    private CartList cartList;
    private Scanner scanner;
    private boolean running;
    public MainSystem() {
        this.goodsManager = new GoodsManager();
        this.cartList = new CartList();
        this.scanner = new Scanner(System.in);
        this.running = true;
    }
    //显示菜单
    public void showMenu() throws IOException {
        anner:while (true) {
            System.out.println("*****欢迎进入京东商城*****");
            System.out.println("1.添加商品");
            System.out.println("2.查看所有商品");
            System.out.println("3.查看指定编号商品");
            System.out.println("4.添加到购物车");
            System.out.println("5.显示购物车");
            System.out.println("6.退出");
            System.out.println("******************************");
            System.out.print("请选择菜单: ");
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    goodsManager.addGoods();
                    break;
                case 2:
                    goodsManager.queryAllGoods();
                    break;
                case 3:
                    goodsManager.findProductById();
                    break;
                case 4:
                    addCart();
                    break;
                case 5:
                    cartList.showCart();
                    break;
                case 6:
                    exit();
                    break anner;
                default:
                    System.out.println("输入错误！请重新输入！");
                    break;
            }
        }
    }

    //添加到购物车
    private void addCart() {
        System.out.print("请输入商品编号：");
        String id = scanner.next();
        Goods goods = goodsManager.findProductById(id);
        if (goods == null) {
            System.out.println("商品不存在！");
            return;
        }
        System.out.println("请输入商品数量：");
        int count = scanner.nextInt();
        if (count <= 0) {
            System.out.println("商品数量不能小于1！");
            return;
        }
        cartList.addCart(goods, count);
    }
        //退出程序
    public void exit() throws IOException {
        running = false;
        goodsManager.saveGoodsToFile();
        cartList.saveCartToFile();
        System.out.println("已退出系统！");
    }
    //运行系统
    public void run() throws IOException, ClassNotFoundException {
        //从文件加载数据
        goodsManager.loadGoodsFromFile();
        cartList.loadCartFromFile(goodsManager);
        while (running) {
            showMenu();
        }
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        MainSystem mainSystem = new MainSystem();
        mainSystem.run();
    }

}
//商品类
class Goods implements Serializable {
    private static final long serialVersionUID = 1L;
    //商品编号
    private String id;
    //商品名称
    private String name;
    //商品价格
    private double price;
    //商品颜色
    private String color;
    //商品尺寸
    private String size;
    //商品库存
    private int stock;
    //无参构造方法
    public Goods() {
    }
    //有参构造方法
    public Goods(String id, String name, double price, String color, String size, int stock) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.color = color;
        this.size = size;
        this.stock = stock;
    }
    //getter 和 setter 方法
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public int getStock() {
        return stock;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }
    //重写equals和hashCode方法
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Goods goods = (Goods) o;
        return Double.compare(goods.price, price) == 0 && stock == goods.stock && Objects.equals(id, goods.id) && Objects.equals(name, goods.name) && Objects.equals(color, goods.color) && Objects.equals(size, goods.size);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, price, color, size, stock);
    }
    //重写toString方法
    @Override
    public String toString() {
        return "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", color='" + color + '\'' +
                ", size='" + size + '\'' +
                ", stock=" + stock;
    }
}

//购物车条目类
class Cart implements Serializable{
    private static final long serialVersionUID = 1L;
    //商品对象
    private Goods goods;
    //数量
    private int count;
    //无参构造方法
    public Cart() {
    }
    //有参构造方法
    public Cart(Goods goods, int count) {
        this.goods = goods;
        this.count = count;
    }
    //getter 和 setter 方法
    public Goods getGoods() {
        return goods;
    }

    public void setGoods(Goods goods) {
        this.goods = goods;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
    //重写equals和hashCode方法
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Cart cart = (Cart) o;
        return count == cart.count && Objects.equals(goods, cart.goods);
    }

    @Override
    public int hashCode() {
        return Objects.hash(goods, count);
    }
    //重写toString方法
    @Override
    public String toString() {
        return "Cart{" +
                "goods=" + goods +
                ", count=" + count +
                '}';
    }
}
//购物车类
class CartList implements Serializable{
    private static final long serialVersionUID = 1L;
    //购物车集合
    private Set<Cart> carts;
    private static final String CART_FILE = "cart.dat";
    //无参构造方法
    public CartList() {
        this.carts = new HashSet<>();
    }
    //添加商品到购物车
    public boolean addCart(Goods goods, int count) {
        if (goods == null || count <= 0){
            return false;
        }
        //检查库存是否足够
        if (goods.getStock() < count){
            System.out.println("库存不足!当前库存："+goods.getStock());
            return false;
        }
        //判断购物车中是否有此商品
        Cart cart = new Cart(goods, count);
        //使用迭代器查找是否已存在相同商品
        Iterator<Cart> iterator = carts.iterator();
        while (iterator.hasNext()) {
            Cart c = iterator.next();
            if (c.equals(cart)) {
                //如果已存在相同商品，则更新数量
                c.setCount(c.getCount() + count);
                //更新库存
                goods.setStock(goods.getStock() - count);
                return true;
            }
        }
        //如果没有相同商品，则添加
        carts.add(cart);
        System.out.println("添加成功！");
        return true;
    }
    //显示购物车内容
    public void showCart() {
        if (carts.isEmpty()){
            System.out.println("购物车为空！");
            return;
        }
        System.out.println("编号    商品名称         商品价格  数量    小计");
        double total = 0;
        for (Cart cart : carts) {
            System.out.println(cart);
            total +=cart.getCount()*cart.getGoods().getPrice();
        }
        System.out.println("总价："+total);
    }
    //获取购物车中商品数量
    public int getCartCount() {
        return carts.size();
    }
    //清空购物车
    public void clearCart() {
        carts.clear();
        System.out.println("购物车已清空！");
    }
    //获取购物车条目集合
    public Set<Cart> getCarts() {
        return new HashSet<>(carts);
    }
    //保存购物车到文件
    public void saveCartToFile() throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(CART_FILE))) {
            oos.writeObject(carts);
            System.out.println("购物车已保存到文件！");
        } catch (IOException e) {
            System.out.println("保存购物车失败！"+e.getMessage());
        }
    }
    //从文件中加载购物车
    public void loadCartFromFile(GoodsManager goodsManager) throws IOException, ClassNotFoundException {
        File file = new File(CART_FILE);
        if (!file.exists()) {
            System.out.println("购物车文件不存在！");
            return;
        }
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(CART_FILE))) {
            carts = (Set<Cart>) ois.readObject();
            System.out.println("购物车已从文件中加载！");
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("加载购物车失败！"+e.getMessage());
            carts = new HashSet<>();
        }
    }
}
//商品管理类
class GoodsManager implements Serializable{
    private static final long serialVersionUID = 1L;
    //商品集合
    private Set<Goods> goods;
    private Scanner scanner;
    private static final String GOODS_FILE = "goods.dat";
    public GoodsManager() {
        this.goods = new HashSet<>();
        this.scanner = new Scanner(System.in);
        //初始化一些示例商品
        initializeSampleGoods();

    }
    //初始化示例商品
    private void initializeSampleGoods() {
        goods.add(new Goods("1111", "蜘蛛王皮鞋", 238.0, "黑色", "42", 100000));
        goods.add(new Goods("3333", "Thinkpad x240", 5939.0, "黑色", "12", 50));
        goods.add(new Goods("2222", "iPhone 7plus", 5686.0, "白色", "5", 50000));
    }
    //添加商品
    public void addGoods() {
        System.out.println("请输入商品编号");
        String id = scanner.next();

        // 检查商品编号是否已存在
        if (findProductById(id) != null) {
            System.out.println("商品编号已存在！");
            return;
        }

        System.out.println("请输入商品名称");
        String name = scanner.next();

        System.out.println("请输入商品价格");
        double price = scanner.nextDouble();

        System.out.println("请输入商品颜色");
        String color = scanner.next();

        System.out.println("请输入商品尺寸");
        String size = scanner.next();

        System.out.println("请输入商品库存");
        int stock = scanner.nextInt();

        Goods product = new Goods(id, name, price, color, size, stock);
        goods.add(product);
        System.out.println("添加成功！");
    }
    //根据编号查找商品
    public void findProductById() {
        System.out.println("请输入要查询的商品编号");
        String id = scanner.next();

        Goods product = findProductById(id);
        if (product != null) {
            System.out.println("==================================================");
            System.out.println("编号  商品名称              价格    颜色  尺寸  库存");
            System.out.println("==================================================");
            System.out.println(product);
            System.out.println("==================================================");
        } else {
            System.out.println("未找到该商品！");
        }
    }
    //根据商品编号查找商品(内部方法)
    public Goods findProductById(String id) {
        for (Goods product : goods) {
            if (product.getId().equals(id)) {
                return product;
            }
        }
        return null;
    }
    //查询所有商品
    public void queryAllGoods() {
        if (goods.isEmpty()){
            System.out.println("没有商品信息！");
            return;
        }
        System.out.println("编号    商品名称         商品价格  商品颜色  商品尺寸  库存");
        for (Goods product : goods) {
            System.out.println(product);
        }
    }
    //获取商品集合
    public Set<Goods> getGoods() {
        return new HashSet<>(goods);
    }
    //保存商品到文件
    public void saveGoodsToFile() throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(GOODS_FILE))) {
            oos.writeObject(goods);
            System.out.println("商品已保存到文件！");
        } catch (IOException e) {
            System.out.println("保存商品失败！"+e.getMessage());
        }
    }
    //从文件中加载商品
    public void loadGoodsFromFile() throws IOException, ClassNotFoundException {
        File file = new File(GOODS_FILE);
        if (!file.exists()) {
            System.out.println("商品文件不存在！");
            return;
        }
    }
}